package d0330;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class TCPServer {
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        try {
            serverSocket=new ServerSocket(4700);
            System.out.println("服务器启动成功");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("服务器启动失败");
        }
        //调用accept放大，可以接受客户端请求，并返回当前socket对象
        Socket socket = null;
        try {
            socket = serverSocket.accept ();
            System.out.println ("连接成功" );
        } catch (IOException e) {
            e.printStackTrace ( );
        }

        String line;
        try {
            //接收客户端输入内容
            DataInputStream is=new DataInputStream(socket.getInputStream());
            //输出内容到客户端
            DataOutputStream os=new DataOutputStream(socket.getOutputStream());

            System.out.println("Client:"+is.readUTF());//输出客户端发送的内容
            BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
            line=sin.readLine();
            while(!line.equals("exit")){
                os.writeUTF(line);//向客户端写入数据
                os.flush();//把缓存内容提交
                System.out.println("Client:"+is.readUTF());
                line=sin.readLine();
                 }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
